package org.dromara.oce.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileUtil {

    public static File convertToFile(MultipartFile multipartFile) {
        File file = null;
        try {
            file = new File(multipartFile.getOriginalFilename());
            try (InputStream inputStream = multipartFile.getInputStream();
                 OutputStream outputStream = new FileOutputStream(file)) {
                int read;
                byte[] bytes = new byte[1024];
                while ((read = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return file;
    }

    /**
     * 生成文件的MD5值
     *
     * @param file 上传文件
     * @return 文件的MD5值
     */
    public static String getFileMD5(MultipartFile file) {
        InputStream fis = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            fis = file.getInputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) != -1) {
                md.update(buffer, 0, length);
            }
            byte[] digest = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
